import 'dart:convert';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:sports_new/base/base_controller.dart';
import 'package:sports_new/entity/other/resource_entity.dart';
import 'package:sports_new/widgets/share/share_sheet.dart';
import 'package:umeng_apm_sdk/umeng_apm_sdk.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:sports_new/controller/my/login_logic.dart';
import 'package:sports_new/entity/other/app_update_entity.dart';
import 'package:sports_new/controller/service/resource_service.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/sp_utils.dart';
import 'package:sports_new/utils/user.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/view/my/my_web_page.dart';
import '../../server/api/other_api.dart';
import '../../server/api/pay_api.dart';
import '../../server/api/user_api.dart';
import '../../entity/pay/my_coupon.dart';
import '../../widgets/base/qkd_dialog.dart';
import '../service/umeng_service.dart';

class MyPageLogic extends BaseController {
  final scrollC = ApmScrollController();
  final EasyRefreshController refreshC = EasyRefreshController();
  bool _onRefresh = false;
  static double originHeaderBgHeight = Get.width / 0.9375;
  late RxDouble headerBgHeight;
  List<MyCouponEntity>? _coupons;
  List<ResourceEntity>? activeMenu;
  AppUpdateEntity? versionInfo;
  bool hasNewVersion = false;

  bool get onRefresh => _onRefresh;
  List<MyCouponEntity>? get coupons => _coupons;

  set coupons(List<MyCouponEntity>? value) {
    _coupons = value;
    update();
  }
  set onRefresh(bool value) {
    _onRefresh = value;
    update();
  }

  @override
  void onInit() {
    super.onInit();
    headerBgHeight = originHeaderBgHeight.obs;
    scrollC.addListener(() {
      if (scrollC.offset < 0) {
        double offset = scrollC.offset < -100 ? -100 : scrollC.offset;
        headerBgHeight.value = originHeaderBgHeight - offset;
      }
    });
    checkVersion();
  }

  @override
  void onReady() async{
    super.onReady();
    getMenu();
    getCoupon();
  }

  Future getCoupon() async{
    if(User.isLogin) {
      coupons = await PayApi.myCoupons() ?? [];
    }else{
      coupons = [];
    }
  }

  Future getMenu() async{
    var list = await OtherApi.getAppList("app_my_item");
    activeMenu = list?.where((element) => element.button == "my_item").toList();
    update();
  }

  Future getData() async{
    await User.fetchUserInfo();
    if (User.isLogin) {
      coupons = await PayApi.myCoupons() ?? [];
    }
    update();
  }

  void doRefresh(){
    if(refreshC.headerState?.mode.isIdle == false) return;
    refreshC.callRefresh();
  }

  tapMyCollection() {
    Utils.onEvent("my_collection");
    User.needLogin(() => Get.toNamed(Routes.myCollection));
  }

  tapMyFocus() {
    Utils.onEvent("my_follow");
    User.needLogin(() => Get.toNamed(Routes.myFocus));
  }

  tapExpert() {
    Utils.onEvent("my_expert_joinin");
    User.needLogin(() => Get.toNamed(Routes.expertRequestType));
  }

  // tapShare() => Utils.share();
  tapContact() {
    Utils.onEvent("my_custom_service");
    Get.toNamed(Routes.myContact);
  }

  tapPushSetting() {
    Utils.onEvent("tssz");
    Get.toNamed(Routes.myPushSetting);
  }

  tapSettings() {
    Utils.onEvent("my_settings");
    if(hasNewVersion){
      SpUtils.versionIgnore = versionInfo?.latestVersion;
    }
    checkVersion();
    Get.toNamed(Routes.mySetting);
  }

  tapLive() async{
    Utils.onEvent("zjzb");
    if(User.isPersonVerified){
      Get.toNamed(Routes.expertRooms);
    }else {
      Get.dialog(
          const QkdDialog.alert("实名认证",
              content: "根据《互联网信息服务管理办法》，直播需要实名认证哦",
              confirmText: "立即认证"
          ),
          barrierDismissible: false
      ).then((value) {
        if (value is bool && value) {
          Get.toNamed(Routes.accountVerify);
        }
      });
    }
  }

  tapRecharge({bool coin = false}) {
    Utils.onEvent(coin?"my_coin":'my_charge');
    User.needLogin(
          () async {
        await Get.toNamed(Routes.myRecharge);
        update();
      },
    );
  }

  tapVip(){
    Utils.onEvent('my_vip_open');
    Get.toNamed(Routes.vipCenter);
  }

  tapPurchase(){
    Utils.onEvent("my_order");
    User.needLogin(() => Get.toNamed(Routes.myPurchase),
      fail: Get.back);
  }

  tapCoupons(){
    Utils.onEvent("my_coupon");
    User.needLogin(() => Get.toNamed(Routes.myCoupons),
      fail: Get.back);
  }

  tapQuestion() {
    Utils.onEvent("my_feedback");
    Get.toNamed(Routes.help);
  }

  tapHeaderName() async{
    if (User.isLogin) {
      Utils.onEvent('my_page');
      Get.toNamed(Routes.userPage,
          arguments: User.info?.id, parameters: {'type': '1'});
    } else {
      Utils.onEvent('wode_pd_dl');
      await Utils.login();
      // User.needLogin(() => User.fetchUserInfos().then((value) => update()));
    }
  }

  tapTask() {
    Utils.onEvent("my_signin");
    User.needLogin(() => Get.toNamed(Routes.homeTask));
  }

  tapShare() async {
    if(SpUtils.shareClick == false) SpUtils.shareClick = true;
    List<ResourceEntity>? list = await OtherApi.getAppList("fxlb");
    String url = list?.firstWhere((e) => e.button == "邀请页链接").content ?? "";
    if(url.noValue) return;
    Get.toNamed(
      Routes.webview,
      arguments: WebPara(url,title: "邀请得球币")
    );
  }

  void getMyCoupon() async {
    if (User.isLogin) {
      await UserApi.joinActivity('invite1');
      Get.find<ResourceService>().getAppLoginConfig().then((value) {
        update();
      });
    }
  }

  Future checkVersion() async{
    PackageInfo.fromPlatform().then((value) async{
      versionInfo = await OtherApi.checkUpdate(value.version);
      hasNewVersion =
        (versionInfo?.needUpdate ?? 0) > 0 &&
          versionInfo?.latestVersion != SpUtils.versionIgnore;
      update();
    });
  }

  @override
  void getRefresh() async{
    onRefresh = true;
    await User.fetchUserInfo();
    if (User.isLogin) {
      coupons = await PayApi.myCoupons() ?? [];
    }
    update();
    onRefresh = false;
  super.getRefresh();
  }
}
